package manager.server.factory{
	import com.debug.TDebug;
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	import manager.server.event.SocketEvent;
	import org.adobe.utils.ObjectUtils;
	import org.adobe.utils.Singleton;

	/**
	 * byteArray区别类型并将其装入工厂的指令库中
	 *
	 */
	public class CommandFactory extends EventDispatcher {
		//指令集
		private static var socketCmds:Array = [];

		public function CommandFactory(){
		}
		
		/**
		 * 根据cmd类型，解析bytes
		 * @param byteArray
		 */		
		public static function decodeSocketData(byteArray:ByteArray):void {
			var socket_cmd:ISocketCommand = null;
			var copyByte:ByteArray = ObjectUtils.copy(byteArray) as ByteArray;  //对象复制
			var byte:ByteArray 	   = ObjectUtils.copy(byteArray) as ByteArray;  //对象复制
			//TDebug.trace("解析后内容：" + byte.readShort(),byte.readUTF());
			
			var cmd:int = copyByte.readShort();
			switch (cmd){
				case Commands.LOGIN:	//登陆
					socket_cmd = new LoginCommand().decodeSocketData(byteArray);
					break;
				case Commands.SEND_MSG: //发送信息
					socket_cmd = new SendCommand().decodeSocketData(byteArray);
					break;
				case Commands.EXIT:		//退出
					socket_cmd = new ExitCommand().decodeSocketData(byteArray);
					break;
			}
			socketCmds.push(socket_cmd);
			//派发Ready
			Singleton.getInstance().dispatchEvent(new SocketEvent(SocketEvent.READY, 
													{cmd: cmd, socketData: byteArray}));
		}

		/**
		 * 根据指令获取相应的指令对象 
		 * @param cmd
		 * @return 
		 */		
		public static function getCommandByType(cmd:int):ISocketCommand {
			var socketCommand:ISocketCommand;
			for (var i:int = 0; i < socketCmds.length; i++){
				if (socketCmds[i].type == cmd){
					socketCommand = socketCmds[i];
				}
			}
			return socketCommand;
		}

		/**删除指定指令的指令对象**/
		private function delCommand(cmd:int):void {
			for (var i:int = 0; i < socketCmds.length; i++){
				if (socketCmds[i].type == cmd){
					socketCmds.splice(i, 1);
				}
			}
		}
	}
}